package com.wanchuang.qhbb.module.policy;

/**
 * 文件名 : EaringDetailFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/11/28 20:47
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.wanchuang.qhbb.R;
import com.wanchuang.qhbb.adapter.PolicyAdapter;
import com.wanchuang.qhbb.adapter.PolicyPeopleBean;
import com.wanchuang.qhbb.adapter.PolicySelectBean;
import com.wanchuang.qhbb.base.BaseFragment;
import com.wanchuang.qhbb.dialog.PolicyDialog;
import com.wanchuang.qhbb.help.UserHelper;
import com.wanchuang.qhbb.net.Apis;
import com.wanchuang.qhbb.net.NetworkManager;
import com.wanchuang.qhbb.net.WebApis;
import com.wanchuang.qhbb.net.interfaces.OnRequestCallBack;
import com.wanchuang.qhbb.proto.AgentPolicy;
import com.wanchuang.qhbb.utils.GsonUtils;
import com.wanchuang.qhbb.utils.ValidateUtils;
import com.wanchuang.qhbb.view.LoadMoreBottomView;
import com.wanchuang.qhbb.view.pinnedheader.PinnedHeaderItemDecoration;
import com.wanchuang.qhbb.view.pinnedheader.PinnedHeaderRecyclerView;
import com.wanchuang.qhbb.view.pinnedheader.SideBar;
import com.wanchuang.qhbb.web.ui.WebViewActivity;
import com.google.protobuf.InvalidProtocolBufferException;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import kale.ui.view.dialog.EasyDialog;

public class PolicyPeopleFragment extends BaseFragment implements PolicyAdapter.OnItemClickListener {

    Unbinder unbinder;
    @BindView(R.id.recycler_linear)
    PinnedHeaderRecyclerView recyclerLinear;
    @BindView(R.id.sidebar)
    SideBar sidebar;
    @BindView(R.id.tv_ti_shi)
    TextView tvTiShi;
    @BindView(R.id.empty_view)
    LinearLayout emptyView;

    @BindView(R.id.refreshLayout)
    TwinklingRefreshLayout mRefreshLayout;
    private int position;


    private List<PolicyPeopleBean> dataList = new ArrayList<>();
    private List<PolicySelectBean> selectBeans = new ArrayList<>();

    private List<String> sortList = new ArrayList<>();
    private LinearLayoutManager layoutManager;
    private PolicyAdapter adapter;


    public static PolicyPeopleFragment NewInstance(int instanceType) {
        Bundle bundle = new Bundle();
        bundle.putInt("position", instanceType);
        PolicyPeopleFragment messageTypeFragment = new PolicyPeopleFragment();
        messageTypeFragment.setArguments(bundle);
        return messageTypeFragment;
    }


    /**
     * 获取布局文件
     *
     * @return
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_policy_people;
    }


    /**
     * 初始化操作步骤
     */
    @Override
    protected void init() {
        unbinder = ButterKnife.bind(this, rootView);
        position = getArguments().getInt("position");
    }

    /**
     * 初始化界面
     */
    @Override
    protected void initView() {
        initRecycle();
        initData();
        initRefresh();
    }

    /**
     * 实例化线性底部RecyclerView
     * *
     */
    private void initRecycle() {
        sidebar.setTextView(tvTiShi);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerLinear.setLayoutManager(layoutManager);
        sidebar.setOnTouchingLetterChangedListener(s -> {
            for (int i = 0; i < dataList.size(); i++) {
                if (dataList.get(i).getMember_name().equals(s)) {
                    layoutManager.scrollToPositionWithOffset(i, 0);
                    break;
                }
            }
        });
        adapter = new PolicyAdapter(dataList, this);
    }

    private void initData() {
        AgentPolicy.agent_policys.Builder builder = AgentPolicy.agent_policys.newBuilder();
        builder.setType(String.valueOf(position));
        NetworkManager.INSTANCE.post(Apis.agent_policys, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                AgentPolicy.agent_policys result = AgentPolicy.agent_policys.parseFrom(bytes);
                List<AgentPolicy.agent_policys.list_member_part> list_parts = result.getListPartList();
                for (int i = 0; i < list_parts.size(); i++) {
                    PolicyPeopleBean titleBean = new PolicyPeopleBean();
                    titleBean.setMember_name(list_parts.get(i).getFirstCharter());
                    titleBean.setType(1);  // 标题type
                    dataList.add(titleBean);
                    sortList.add(list_parts.get(i).getFirstCharter());
                    for (int j = 0; j < list_parts.get(i).getMemberInfoList().size(); j++) {
                        PolicyPeopleBean contentBean = new PolicyPeopleBean();
                        contentBean.setType(0);
                        contentBean.setMember_name(list_parts.get(i).getMemberInfoList().get(j).getMemberName());
                        contentBean.setMember_id(list_parts.get(i).getMemberInfoList().get(j).getMemberId());
                        contentBean.setIs_new(list_parts.get(i).getMemberInfoList().get(j).getIsNew());
                        contentBean.setMember_mobile(list_parts.get(i).getMemberInfoList().get(j).getMemberMobile());
                        contentBean.setAdd_time(list_parts.get(i).getMemberInfoList().get(j).getMemberAddtime());
                        dataList.add(contentBean);
                    }
                }
                recyclerLinear.setAdapter(adapter);
                recyclerLinear.addItemDecoration(new PinnedHeaderItemDecoration());
                sidebar.setList(sortList);
                if (ValidateUtils.isValidate(dataList)) {
                    recyclerLinear.setVisibility(View.VISIBLE);
                    emptyView.setVisibility(View.GONE);
                } else {
                    recyclerLinear.setVisibility(View.GONE);
                    emptyView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(int code, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    public void reRoadData() {
        dataList.clear();
        sortList.clear();
        adapter.notifyDataSetChanged();
        initData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onClick(View v, String member_id, String name, String phone, String time) {
        if (position == 2) {
            if (member_id.equals(UserHelper.getUser().getMember_id())) {
                WebViewActivity.startActivity(mContext, WebApis.policyRevision + "?type=1" + "&memberId=" + member_id + "&memberName=" + name);
            } else {
                WebViewActivity.startActivity(mContext, WebApis.policyRevision + "?type=2" + "&memberId=" + member_id + "&memberName=" + name);
            }
        } else {
            AgentPolicy.policy_goods.Builder builder = AgentPolicy.policy_goods.newBuilder();
            builder.setMemberId(member_id);
            NetworkManager.INSTANCE.post(Apis.policy_goods, builder.build().toByteArray(), new OnRequestCallBack() {
                @Override
                public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                    selectBeans.clear();
                    AgentPolicy.policy_goods result = AgentPolicy.policy_goods.parseFrom(bytes);
                    List<AgentPolicy.policy_goods_tab> list_parts = result.getGoodsListList();
                    for (int i = 0; i < list_parts.size(); i++) {
                        PolicySelectBean itemBean = new PolicySelectBean();
                        itemBean.setTitle(list_parts.get(i).getTabName());
                        itemBean.setIsTitle(true);
                        selectBeans.add(itemBean);
                        for (int j = 0; j < list_parts.get(i).getGoodsListList().size(); j++) {
                            PolicySelectBean tempBean = new PolicySelectBean();
                            tempBean.setItem(list_parts.get(i).getGoodsListList().get(j));
                            selectBeans.add(tempBean);
                        }
                    }
                    PolicyDialog.Builder builder = new PolicyDialog.Builder(mContext);
                    builder.setData(selectBeans);
                    builder.setOnDialogClickListener((v1, positon) -> {
                        for (PolicySelectBean selectBean : selectBeans) {
                            if (selectBean.isSelect()) {
                                Intent intent = new Intent(mContext, PolicyShareActivity.class);
                                intent.setAction(GsonUtils.serializedToJson(selectBeans));
                                intent.setType(member_id);
                                intent.putExtra("name", name + " " + phone);
                                intent.putExtra("time", time);
                                startActivity(intent);
                                break;
                            }
                        }
                    });
                    EasyDialog build = builder.build();
                    build.setCancelable(true);
                    build.show(getFragmentManager());
                }

                @Override
                public void onError(int code, String errorMessage) {
                    showToast(errorMessage);
                }
            });
        }
    }


    /**
     * 实例化下拉Refresh
     * *
     */
    private void initRefresh() {
        SinaRefreshView header = new SinaRefreshView(mContext);
        header.setArrowResource(R.mipmap.refresh_arrow);
        header.setBackgroundResource(R.color.backgroundColor);
        TextView refreshTextView = header.findViewById(com.lcodecore.tkrefreshlayout.R.id.tv);
        refreshTextView.setTextSize(14);
        mRefreshLayout.setHeaderView(header);
        LoadMoreBottomView bottom = new LoadMoreBottomView(mContext);
        mRefreshLayout.setBottomView(bottom);
        mRefreshLayout.setEnableLoadmore(false);
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {

                AgentPolicy.agent_policys.Builder builder = AgentPolicy.agent_policys.newBuilder();
                builder.setType(String.valueOf(position));
                NetworkManager.INSTANCE.post(Apis.agent_policys, builder.build().toByteArray(), new OnRequestCallBack() {
                    @Override
                    public void onOk(byte[] bytes) throws InvalidProtocolBufferException {

                        dataList.clear();
                        sortList.clear();
                        adapter.notifyDataSetChanged();

                        AgentPolicy.agent_policys result = AgentPolicy.agent_policys.parseFrom(bytes);
                        List<AgentPolicy.agent_policys.list_member_part> list_parts = result.getListPartList();
                        for (int i = 0; i < list_parts.size(); i++) {
                            PolicyPeopleBean titleBean = new PolicyPeopleBean();
                            titleBean.setMember_name(list_parts.get(i).getFirstCharter());
                            titleBean.setType(1);  // 标题type
                            dataList.add(titleBean);
                            sortList.add(list_parts.get(i).getFirstCharter());
                            for (int j = 0; j < list_parts.get(i).getMemberInfoList().size(); j++) {
                                PolicyPeopleBean contentBean = new PolicyPeopleBean();
                                contentBean.setType(0);
                                contentBean.setMember_name(list_parts.get(i).getMemberInfoList().get(j).getMemberName());
                                contentBean.setMember_id(list_parts.get(i).getMemberInfoList().get(j).getMemberId());
                                contentBean.setIs_new(list_parts.get(i).getMemberInfoList().get(j).getIsNew());
                                contentBean.setMember_mobile(list_parts.get(i).getMemberInfoList().get(j).getMemberMobile());
                                contentBean.setAdd_time(list_parts.get(i).getMemberInfoList().get(j).getMemberAddtime());
                                dataList.add(contentBean);
                            }
                        }
                        sidebar.setList(sortList);
                        if (ValidateUtils.isValidate(dataList)) {
                            recyclerLinear.setVisibility(View.VISIBLE);
                            emptyView.setVisibility(View.GONE);
                        } else {
                            recyclerLinear.setVisibility(View.GONE);
                            emptyView.setVisibility(View.VISIBLE);
                        }
                        mRefreshLayout.finishRefreshing();
                    }

                    @Override
                    public void onError(int code, String errorMessage) {
                        showToast(errorMessage);
                    }
                });


            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {

            }
        });
    }
}
